package com.itmuch.icms.controller.front.common;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.itmuch.icms.channel.domain.Channel;
import com.itmuch.icms.channel.service.IChannelService;
import com.itmuch.icms.content.domain.Content;
import com.itmuch.icms.content.domain.ContentTxt;
import com.itmuch.icms.content.service.IContentService;
import com.itmuch.icms.content.service.IContentTxtService;

@Controller
public class DynamicPageController {
    @Resource
    private IChannelService channelService;
    @Resource
    private IContentService contentService;
    @Resource
    private IContentTxtService contentTxtService;

    /**
     * 用于栏目页/文章页带分页的情况
     * @param type 类型：channel栏目 content内容 
     * @param id type为栏目时指栏目id type为内容时指内容id
     * @param page 页码
     * @param request 请求
     * @param map 视图
     * @return 模板路径
     */
    @RequestMapping(value = { "/{type}/{id:[1-9]\\d*}/{page:[1-9]\\d*}" }, method = RequestMethod.GET)
    public String dynamic(@PathVariable("type") String type, @PathVariable("id") Integer id, @PathVariable("page") Integer page,
            HttpServletRequest request, ModelMap map) {
        map.put("pageNo", page);

        return this.selectTplByTypeAndId(type, id, request, map);
    }

    /**
     * 用于栏目页/文章页第一页的情况
     * @param type 类型：channel栏目 content内容 
     * @param id type为栏目时指栏目id type为内容时指内容id
     * @param request 请求
     * @return 模板路径
     */
    @RequestMapping(value = "/{type}/{id:[1-9]\\d*}", method = RequestMethod.GET)
    public String dealDynamic(@PathVariable String type, @PathVariable("id") Integer id, HttpServletRequest request, ModelMap map) {
        map.put("pageNo", 1);
        return this.selectTplByTypeAndId(type, id, request, map);

    }

    private String selectTplByTypeAndId(String type, Integer id, HttpServletRequest request, ModelMap map) {
        Channel channel = null;
        if ("channel".equals(type)) {
            // 路径，用于分页的时候
            map.put("path", new StringBuffer(request.getContextPath() + "/channel/" + id + "/"));
            channel = this.channelService.selectById(id);
            request.setAttribute("channel", channel);
            return channel.getTemplateName() + channel.getTemplateFile();
        } else if ("content".equals(type)) {
            Content content = this.contentService.selectById(id);
            // 如果文章不存在或者文章的状态不是审核通过，直接跳到404
            if ((content == null) || (content.getStatus() != 1)) {
                return "error/404";
            }
            channel = this.channelService.selectById(content.getChannelId());
            ContentTxt contentTxt = this.contentTxtService.selectByContentId(content.getId());
            String txt = null;
            if (contentTxt != null) {
                txt = contentTxt.getTxt();
            }
            request.setAttribute("content", content);
            request.setAttribute("txt", txt);
            request.setAttribute("channel", channel);
            return channel.getTemplateName() + "/content/news";
        }
        return "error/404";
    }
    //    @RequestMapping(value = "/**", method = RequestMethod.GET)
    //    public String dynamic(HttpServletRequest request, ModelMap map) {
    //        String path = this.getPath(request);
    //
    //        if (path == null) {
    //            throw new IllegalArgumentException("URI can not be null");
    //        }
    //        if (!path.startsWith("/")) {
    //            throw new IllegalArgumentException("URI must start width '/'");
    //        }
    //        int line = path.indexOf("-");
    //        // 获得路径信息
    //        String pathStr;
    //        String pageNoStr;
    //        if (line != -1) {
    //            pathStr = path.substring(0, line);
    //            pageNoStr = path.substring(line + 1);
    //
    //            // 只要放入map中，那么使用TemplateModel pageNo = env.getGlobalVariable("pageNo");
    //            // 即可获得页码了。
    //            // TODO 等待完善，例如转换错误等
    //            map.put("pageNo", Integer.parseInt(pageNoStr));
    //        } else {
    //            pathStr = path;
    //        }
    //        String[] paths = StringUtils.split(pathStr, '/');
    //        // 认为是栏目或者是单页
    //        // TODO 单页的情况
    //        Channel channel = null;
    //        if (paths.length == 1) {
    //            channel = this.channelService.selectByPath(paths[0]);
    //            return channel.getTemplateName() + channel.getTemplateFile();
    //        }
    //        // 认为是文章 文章url:栏目名称/文章id
    //        else {
    //            try {
    //                int id = Integer.parseInt(paths[1]);
    //                Content content = this.contentService.selectById(id);
    //                channel = this.channelService.selectById(content.getChannelId());
    //                // 当且仅当传过来的栏目名称 == 通过文章id查出来的栏目名称时，才展示文章，否则跳到404；这么做防止多入口
    //                if (paths[0].equals(channel.getPath())) {
    //                    ContentTxt contentTxt = this.contentTxtService.selectByContentId(content.getId());
    //                    String txt = null;
    //                    if (contentTxt != null) {
    //                        txt = contentTxt.getTxt();
    //                    }
    //                    request.setAttribute("content", content);
    //                    request.setAttribute("txt", txt);
    //                    return channel.getTemplateName() + "/content/news";
    //                }
    //                return "error/404";
    //
    //            } catch (NumberFormatException e) {
    //                return "error/404";
    //            }
    //        }
    //    }

    //    private String getPath(HttpServletRequest request) {
    //        UrlPathHelper helper = new UrlPathHelper();
    //        String uri = helper.getOriginatingRequestUri(request);
    //        String ctx = helper.getOriginatingContextPath(request);
    //        if (!StringUtils.isBlank(ctx)) {
    //            return uri.substring(ctx.length());
    //        } else {
    //            return uri;
    //        }
    //    }
    //
    //    public static void main(String[] args) {
    //        String s = "^/c/[1-9]\\d*(/[1-9]\\d*)?$";
    //        Pattern pattern = Pattern.compile(s);
    //        Matcher matcher = pattern.matcher("/c/1/1");
    //        System.out.println(matcher.matches());
    //    }
}
